// pages/graphicDetail/graphicDetail.js
const app = getApp();
import LoginStore from '../../pages/login/store.js';
import { proxy, reqHeader, calcTime, isAuthorization, getscene, limitLength, getparamstr, roundRect } from '../../utils/util.js';
import async from '../../libs/async.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    navbarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '', //导航栏 中间的标题
      background: 'linear-gradient(to bottom, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0))',
      hasFilter: true,
      color: '#FFFFFF',
      btnStyle: 'white', //black, white
    },
    navBarHeight: app.globalData.height,
    id: '',
    photoData: {},
    sharePop: false,
    popShow: false,
    popStyle: {
      cls: 'hChange'
    },
    showLikeDetail: false,
    appParams: '',
    options: {},
    canvasHidden: true,
    canvasHeight: 0,
    screenWidth: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let me = this;
    wx.getSystemInfo({
      success: function (res) {
        me.setData({
          screenWidth: res.screenWidth
        });
      }
    });
    if (options.id) {
      aferOnLoad(options);
    } else if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      getparamstr(scene, function (paramStr) {
        if (paramStr.search('&') != -1) {
          let sceneArray = paramStr.split("&");
          options.id = sceneArray[0];
          options.resourceType = sceneArray[1];
          options.type = sceneArray[2];
          if (sceneArray.length == 5) {
            options.fromType = sceneArray[3];
            options.fromResourceId = sceneArray[4];
          }
        }
        aferOnLoad(options);
      })
    }

    function aferOnLoad(options) {
      console.log(options)
      me.setData({
        id: options.id,
        resourceType: options.resourceType, // 2, 3
        appParams: JSON.stringify({
          category: options.resourceType == 2 ? "groupPhotoDetail" : "graphicDetail",
          id: options.id
        }),
        options,
      }, () => {
        me.loadData(options)
      })
    }
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let photoData = this.data.photoData;
    let title = photoData.title;
    if (!title) {
      if (photoData.resourceType == 2) {
        title = photoData.uploaderName + "的作品";
      } else if (photoData.resourceType == 3) {
        title = photoData.uploaderName + "的文章作品";
      }
    } else if (photoData.resourceType == 3) {
      title = `【文章】${title}`
    }
    let opt = this.data.options;
    let path = `pages/graphicDetail/graphicDetail?id=${photoData.id}&resourceType=${photoData.resourceType}&type=share`;
    if (opt.fromType) {
      path += `&fromType=${opt.fromType}`;
    }
    if (opt.fromResourceId) {
      path += `&fromResourceId=${opt.fromResourceId}`;
    }
    console.log(path)
    return {
      title: title,
      path: path,
      imageUrl: photoData.url.baseUrl + '!wechat'
    }
  },
  resolveMsg: function (desc) {
    let msgTextList = [];
    let tplMsgStr = '';
    let res = desc.match(/<a\b[^>]+\bhref="[^"]*"[^>]*\b(?:topic_id|user_id)="[^"]+">[\s\S]*?<\/a>/gi);
    if (res != null) {
      let resList = desc.split(/(<a\b[^>]+\bhref="[^"]*"[^>]*\b(?:topic_id|user_id)="[^"]+">[\s\S]*?<\/a>)/);
      resList.forEach((value, i) => {
        if (value) {
          let hasUser = value.match(/<a\b[^>]+\bhref="[^"]*"[^>]*\buser_id="[^"]+">[\s\S]*?<\/a>/gi);
          let hasTopic = value.match(/<a\b[^>]+\bhref="[^"]*"[^>]*\btopic_id="[^"]+">[\s\S]*?<\/a>/gi);
          if (hasUser != null) {
            let splitRes = value.split(/<a\b[^>]+\bhref="[^"]*"[^>]*\buser_id="([^"]+)">([\s\S]*?)<\/a>/);
            let descStr = splitRes[2];
            if (!msgTextList.length) {
              descStr = descStr.replace(/(^\s*)/g, "");
            };
            msgTextList.push({
              type: 'user',
              desc: descStr,
              id: splitRes[1]
            })
          } else if (hasTopic != null) {
            let splitRes = value.split(/<a\b[^>]+\bhref="[^"]*"[^>]*\btopic_id="([^"]+)">([\s\S]*?)<\/a>/);
            let descStr = splitRes[2];
            if (!msgTextList.length) {
              descStr = descStr.replace(/(^\s*)/g, "");
            };
            msgTextList.push({
              type: 'topic',
              desc: descStr,
              id: splitRes[1]
            })
          } else {
            msgTextList.push({
              type: 'text',
              desc: value
            });
            tplMsgStr += value;
          }
        }
      })

    } else {
      msgTextList.push({
        type: 'text',
        desc: desc
      });
      tplMsgStr += desc;
    }

    return {
      msgTextList,
      tplMsgStr
    }
  },
  turnToLinkDetail(e) {
    let desc = e.currentTarget.dataset.desc;
    if (desc.type === 'topic') {
      wx.navigateTo({
        url: `/pages/topic/topic?topicId=${desc.id}`,
      })
    } else if (desc.type === 'user') {
      wx.navigateTo({
        url: `/pages/userInfo/userInfo?userId=${desc.id}`,
      })
    }
    return
  },
  loadData: function (options) {
    let me = this;
    let userAccountInfo = LoginStore.userInfo || {};
    let params = {
      imgsize: 'p1,p2,p3,p5,p6',
      type: 'json',
      dataType: 'all'
    };
    params['access_token'] = userAccountInfo.access_token;
    let urlStr = `${proxy}/community/v2/graphic/detail/${options.id}`
    if (options.resourceType && options.resourceType == 2) {
      urlStr = `${proxy}/community/v2/groupPhoto/detail/${options.id}`;
    }
    wx.request({
      url: urlStr,
      data: params,
      header: reqHeader,
      success: function (res) {
        res = res.data;
        if (res.status == 200) {
          let uploadTime = new Date(res.data.uploadedDate);
          res.data.afterChangeTime = calcTime(uploadTime);
          res.data.resolvedDescription = {};
          if (res.data.description) {
            res.data.resolvedDescription = me.resolveMsg(res.data.description)
          }
          me.setData({
            photoData: res.data,
          })
        } else {
          console.log(res.message);
        }
      }
    });
  },
  
  toUserInfo: function(e) {
    let userId = '';
    let callback = () => {
      let urlStr = '/pages/userInfo/userInfo?userId=' + userId;
      let pageList = getCurrentPages();
      if (pageList.length >= 8) {
        wx.redirectTo({
          url: urlStr,
        })
      } else {
        wx.navigateTo({
          url: urlStr
        });
      }
    }
    if (e.currentTarget.dataset.userid) {
      userId = e.currentTarget.dataset.userid;
      callback();
    } else {
      if (!isAuthorization(e)) {
        return;
      }

      LoginStore.validateLogin(() => {
        userId = LoginStore.userInfo.userId;
        callback();
      })

    }
  },
  // 组图黑屏页
  turnToBlackdetail: function(e) {
    let item = this.data.photoData;
    if (item.resourceType == 4 ? item.videoInfo.auditState == 0 : item.state == 1) {
      return;
    }

    let urlStr = `/pages/detail/detail?id=${item.id}&resourceType=${item.resourceType}&fromType=${""}&fromResourceId=${""}`;
    let pageList = getCurrentPages();
    if (pageList.length >= 8) {
      wx.redirectTo({
        url: urlStr,
      })
    } else {
      wx.navigateTo({
        url: urlStr
      });
    }
  },
  sharePopShow: function () {
    this.setData({
      sharePop: true
    });
  },
  closeSharePop: function (e) {
    this.setData({
      sharePop: false
    });
    if (e.detail.makePoster) {
      this.makePoster();
    }
  },
  makePoster: function () {
    wx.showLoading({
      title: '生成中...',
      mask: true
    });

    let me = this;
    let photoData = this.data.photoData;

    let opt = this.data.options;
    let paramStr = `${photoData.id}&${photoData.resourceType}&share`;
    if (opt.fromType) {
      paramStr += `&${opt.fromType}`;
    }
    if (opt.fromResourceId) {
      paramStr += `&${opt.fromResourceId}`;
    }
    getscene(paramStr, (scene) => {
      let photo_obj = [{
        url: photoData.url.p3
      }]
      if (photoData.resourceType == 2) {
        photo_obj = [];
        for (let itemValue of photoData.photos) {
          photo_obj.push({
            url: itemValue.url.p3
          })
        }
      }
      let logo_obj = {
        url: 'https://node.500px.me/images/WeChat/logo500.png'
      }
      let avatar_obj = {
        url: photoData.uploaderInfo.avatar.a1 || 'https://node.500px.me/images/WeChat/user.png'
      }
      let erweima_obj = {
        url: `https://node.500px.me/weChat/queryCodeImg?page=pages/graphicDetail/graphicDetail&scene=${scene}`
      }
      async.forEach([...photo_obj, logo_obj, avatar_obj, erweima_obj], (item, callback) => {
        console.log(item)
        wx.getImageInfo({
          src: item.url,
          success: function (res) {
            item.res = res;
            callback();
          },
          fail: function (e) {
            console.log(e)
          }
        });

      }, function () {
        let canvasWidth = me.data.screenWidth;
        let photoHeight = 0;
        if (photo_obj instanceof Array) {
          for (let objItem of photo_obj) {
            let curPhotoHeight = objItem.res.height / objItem.res.width * canvasWidth;
            photoHeight += curPhotoHeight
          }
        }
        let canvasHeight = photoHeight + 123;

        me.setData({
          canvasHidden: false,
          canvasHeight: canvasHeight
        }, () => {
          var context = wx.createCanvasContext('myCanvas');

          context.fillStyle = "#fff";
          context.fillRect(0, 0, canvasWidth + 10, canvasHeight + 10);

          if (photo_obj instanceof Array) {
            let tplHeight = 0
            for (let objItem of photo_obj) {
              let curPhotoHeight = objItem.res.height / objItem.res.width * canvasWidth;
              context.drawImage(objItem.res.path, 0, tplHeight, canvasWidth + 2, curPhotoHeight);
              tplHeight += curPhotoHeight
            }
          }

          context.drawImage(logo_obj.res.path, 16, photoHeight - 30, 203 / 2, 31 / 2);

          if (photoData.resourceType == 3) {
            // 图文
            // context.save();
            // 画圆角矩形
            roundRect(context, canvasWidth - 66, 16, 50, 20, 10, 'rgba(0,0,0,0.3)')

            // // 图文文字
            context.setFontSize(12);
            context.setTextAlign('center');
            context.setTextBaseline('middle');
            context.setFillStyle("#B9C1C7");
            context.fillText('文章', canvasWidth - 41, 26);
            // context.draw()
          }
        

          context.save();
          let r = 10;
          let d = r * 2;
          let cx = 20;
          let cy = photoHeight + 65;
          context.beginPath();
          context.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
          context.setStrokeStyle('#FFFFFF');
          context.stroke();
          context.clip();
          context.drawImage(avatar_obj.res.path, cx, cy, d, d);
          context.restore();

          context.setFontSize(17);
          context.setTextAlign('left');
          context.setTextBaseline('top');
          context.setFillStyle("#525558");
          let titleText = limitLength(photoData.title);
          context.fillText(titleText, 20, photoHeight + 37);

          context.setFontSize(12);
          context.setTextAlign('left');
          context.setTextBaseline('top');
          context.setFillStyle("#B9C1C7");
          let nickNameText = limitLength(photoData.uploaderInfo.nickName);
          context.fillText(nickNameText, 45, photoHeight + 69);

          context.drawImage(erweima_obj.res.path, canvasWidth - 92, photoHeight + 16, 72, 72);

          context.setFontSize(10);
          context.setTextAlign('right');
          context.setTextBaseline('top');
          context.setFillStyle("#525558");
          context.fillText('扫描或长按小程序码', canvasWidth - 11, photoHeight + 93);

          context.draw(false, () => {
            setTimeout(function () {
              wx.canvasToTempFilePath({
                canvasId: 'myCanvas',
                fileType: 'jpg',
                success: function (res) {
                  wx.hideLoading();
                  me.setData({
                    canvasHidden: true
                  });
                  wx.previewImage({
                    current: res.tempFilePath,
                    urls: [res.tempFilePath]
                  })
                },
                fail: function (e) {
                  console.log(e)
                }
              })
            }, 500);
          });
        });
      })
    })

  },
  closeLikePop: function () {
    setTimeout(() => {
      this.setData({
        showLikeDetail: false
      })
    }, 202);
  },
  closePop: function (e) {
    let photoData = this.data.photoData;
    photoData.commentCount = e.detail.curCommentCount;
    setTimeout(() => {
      this.setData({
        popShow: false,
        photoData: photoData
      })
    }, 202);

  },
  commentsHandler: function (e) {
    if (!isAuthorization(e)) {
      return;
    }
    LoginStore.validateLogin(() => {
      let userAccountInfo = LoginStore.userInfo;
      let avatar = "https://img.500px.me/default_tx.png!a1";
      if (userAccountInfo.avatar.a1) {
        avatar = userAccountInfo.avatar.a1;
      }
      this.setData({
        popShow: true,
        popParams: {
          userAvatar: avatar,
          id: this.data.photoData.id,
          uploaderId: this.data.photoData.uploaderId
        }
      });
    })

  },
  likeHandler: function (e) {
    if (!isAuthorization(e)) {
      return;
    }
    let me = this;
    LoginStore.validateLogin(() => {
      let userAccountInfo = LoginStore.userInfo;
      let photoData = this.data.photoData;
      if (userAccountInfo.userId == photoData.uploaderId) {
        me.setData({
          showLikeDetail: true,
          popParams: {
            count: photoData.pictureLikeedCount,
            popKey: "liked",
            curUserId: photoData.id
          }
        })
        return;
      }

      if (photoData.userLikerState == undefined) {
        return;
      }
      let actionFlag = 1;
      if (photoData.userLikerState) {
        actionFlag = 0;
      }
      wx.request({
        url: `${proxy}/community/doLike.do`,
        data: {
          action: actionFlag,
          likedId: photoData.id,
          byAction: userAccountInfo.userId,
          access_token: userAccountInfo.access_token
        },
        header: reqHeader,
        success: function (res) {
          res = res.data;
          if (res.status == 200) {
            if (photoData.userLikerState) {
              photoData.pictureLikeedCount--;
            } else {
              photoData.pictureLikeedCount++;
            }
            photoData.userLikerState = !photoData.userLikerState;
            me.setData({
              photoData: photoData
            });
          } else {
            console.log(res.message);
          }
        }
      });
    })

  },
})